from django.shortcuts import render
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated

from orders.models import OrderInfo
from .models import Payment
from alipay import AliPay
import os


# Create your views here.
class PaymentView(APIView):
    """支付宝的视图"""
    permission_classes = [IsAuthenticated]

    def get(self, request, order_id):
        """获取支付链接"""
        # 1. 判断订单信息是否正确
        try:
            order = OrderInfo.objects.get(pk=order_id, user=request.user,
                                          pay_method=OrderInfo.PAY_METHODS_ENUM["ALIPAY"],
                                          status=OrderInfo.ORDER_STATUS_ENUM["UNPAID"])
        except OrderInfo.DoesNotExist:
            return Response({'message': '订单信息有误'}, status=status.HTTP_400_BAD_REQUEST)

        # 2. 实例化支付宝的操作对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,  # 应用ID
            app_notify_url=None,  # 默认回调url，不需要填写
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            # 应用私钥的路径
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            sign_type="RSA2",  # 签名的加密算法RSA或者RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )

        # 3. 构造支付宝支付链接查询字符串
        # 具体的参数说明：https://docs.open.alipay.com/270/alipay.trade.page.pay
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,  # 订单id
            total_amount=str(order.total_amount),  # 订单金额
            subject="美多商城%s" % order_id,  # 订单标题
            return_url=settings.ALIPAY_CALLBACK_URL + "/pay_success.html",  # 支付成功过以后回调地址
        )

        # 4. 拼接路径
        alipay_url = settings.ALIPAY_URL + "?" + order_string

        return Response({'alipay_url': alipay_url})


class PaymentStatusView(APIView):
    """订单状态保存的视图"""

    def put(self, request):
        # dict()　表示把QueryDict对象转换成普通的字典
        data = request.query_params.dict()
        # 从支付宝返回的响应结果字典中，提取签名字符串出来
        signature = data.pop("sign")

        # 获取支付宝对象 是不是正常的支付
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), "keys/app_private_key.pem"),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                                "keys/alipay_public_key.pem"),  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            sign_type="RSA2",  # RSA 或者 RSA2
            debug=settings.ALIPAY_DEBUG  # 默认False
        )

        success = alipay.verify(data, signature)
        if success:
            # 订单编号
            order_id = data.get('out_trade_no')
            # 支付宝支付流水号
            trade_id = data.get('trade_no')
            Payment.objects.create(
                order_id=order_id,
                trade_id=trade_id
            )

            # 更新订单状态[一旦支付完成以后，就到待发货]
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(
                status=OrderInfo.ORDER_STATUS_ENUM["UNSEND"])

            return Response({'trade_id': trade_id})

        else:
            return Response({'message': '无效请求'}, status=status.HTTP_403_FORBIDDEN)
